package Server;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import java.util.Scanner;
import java.util.TreeMap;

/**
 * 
 * @author cute
 * 
 * 
 *         实现从文件中读入英文文章，统计单词个数,并按值从大到小输出
 */

public class wordNum {

	static class xuehao {
		private static String num;
	}

	public void PutWord(String wenjian, String xuehao) throws Exception {
		Connection conn = null;
		Statement sql;
		ResultSet rs;

		String article = wenjian;
		BufferedReader br = new BufferedReader(new FileReader("/root/图片/" + article));
		List<String> lists = new ArrayList<String>();
		String readLine = null;
		while ((readLine = br.readLine()) != null) {
			String[] wordsArr1 = readLine.split("[^a-zA-Z]");
			for (String word : wordsArr1) {
				if (word.length() != 0) {
					lists.add(word);
				}
			}
		}

		br.close();

		Class.forName("org.mariadb.jdbc.Driver");
		conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/login_word", "test", "123");
		sql = conn.createStatement();

		String command1 = "create table A" + xuehao + "(word varchar(20),number int(15));";
		int ok = sql.executeUpdate(command1);
		sql.close();

		Map<String, Integer> wordsCount = new TreeMap<String, Integer>();

		for (String li : lists) {
			if (wordsCount.get(li) != null) {
				wordsCount.put(li, wordsCount.get(li) + 1);
			} else {
				wordsCount.put(li, 1);
			}

		}

		SortMap(wordsCount, xuehao);

	}

	public void SortMap(Map<String, Integer> oldmap, String xuehao2) {

		Connection conn = null;
		Statement sql = null;
		ResultSet rs;

		ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(oldmap.entrySet());

		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
			@Override
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				return o2.getValue() - o1.getValue(); // 降序
			}
		});

		try {
			Class.forName("org.mariadb.jdbc.Driver");
			try {
				conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/login_word", "test", "123");
			} catch (SQLException e) {

				e.printStackTrace();
			}
			try {
				sql = conn.createStatement();
			} catch (SQLException e) {

				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		}
		for (int i = 0; i < list.size(); i++) {

			String insertsql = "insert into A" + xuehao2 + "(word,number)values(" + "'" + list.get(i).getKey() + "'"
					+ "," + list.get(i).getValue() + ")";

			try {
				int ok = sql.executeUpdate(insertsql);
			} catch (SQLException e) {

				e.printStackTrace();
			}
		}
	}

}